package com.hema.auction.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.adapter.BidRecordAdapter;
import com.hema.auction.base.BaseActivity;
import com.hema.auction.bean.BidRecordInfo;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.widget.view.RefreshRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 竞拍记录
 * author by john
 */

public class BidRecordActivity extends BaseActivity {

    @BindView(R.id.refresh_recycler_view)
    RefreshRecyclerView recyclerView;
    private BidRecordAdapter adapter;
    private List<BidRecordInfo> bidRecordInfos = new ArrayList<>();
    private GoodsInfo info;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_bid_record);
        info = getIntent().getParcelableExtra(Constant.EXTRA_GOOD_INFO);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        recyclerView.setVerLayoutManager();
        adapter = new BidRecordAdapter(bidRecordInfos);
        recyclerView.setAdapter(adapter);
        recyclerView.setOnRefreshListener(this);
        recyclerView.setRefresh(true);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        HttpManager.getInstance(this).getAuctionLog(info.getId(), this);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        try {
            if (result.getInt("errcode") == 0) {
                List<BidRecordInfo> newData = new Gson().fromJson(result.getJSONObject("data").getJSONArray("log").toString(), new TypeToken<List<BidRecordInfo>>() {
                }.getType());
                adapter.setNewData(newData);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        recyclerView.setRefresh(false);
    }
}
